﻿using System;
using System.Web;
using FrameWork.Util.Cookie;
using FrameWork.Util.Extension;
using FrameWork.Util.Http;
using FrameWork.Util.StringOprate;

namespace FrameWork.Context.Oprator
{
    /// <summary>
    /// 操作当前用户信息的类
    /// </summary>
    public class OperatorProvider
    {
        /// <summary>
        /// 获取存储当前用户的对象实例
        /// </summary>
        public static OperatorProvider Provider => new OperatorProvider();

        /// <summary>
        /// 存储用户信息字典的key字符串
        /// </summary>
        private string LoginUserKey => $"{KeyPrefix}_loginuser2";

        /// <summary>
        /// 字典key的前缀
        /// </summary>
        private string KeyPrefix
        {
            get
            {
                var urlHost = Fetch.ServerWholeDomain;
                var urlHostArray = urlHost.Split('.');
                if ((urlHostArray.Length > 1) && !RegExp.IsIp(urlHost))
                {
                    urlHost = urlHost.Remove(urlHost.LastIndexOf(".", StringComparison.Ordinal));
                }
                var keyPrefixPre = urlHost.Replace('.', '_');
                return keyPrefixPre;
            }
        }

        /// <summary>
        /// 获取当前用户的相关信息
        /// </summary>
        public OperatorModel GetCurrent()
        {
            OperatorModel operatorModel;
            if (string.IsNullOrEmpty(Cookie.GetValue(LoginUserKey)))
            {
                operatorModel = null;
            }
            else
            {
                var t = HttpUtility.UrlDecode(Cookie.GetValue(LoginUserKey));
                operatorModel = t.ToObject<OperatorModel>();
            }
            return operatorModel;
        }

        /// <summary>
        /// 存储用户信息到本地cookie中
        /// </summary>
        public void AddCurrent(OperatorModel operatorModel)
        {
            var t = HttpUtility.UrlEncode(operatorModel.ToJson());//进行编码是为了解决汉字乱码的问题
            Cookie.SaveWithMinute(LoginUserKey, t, 600);
        }

        /// <summary>
        /// 移除当前cookie
        /// </summary>
        public void RemoveCurrent()
        {
            Cookie.Remove(LoginUserKey.Trim());
        }

    }
}
